﻿using System;
using System.Data;
using System.Web;
using System.Web.Configuration;
using BLL;
using DAL;
using Ext.Net;
using HTML;

namespace ERP
{
    public partial class Login : System.Web.UI.Page
    {
        #region[Define]
        private readonly Login_User_BLL clsUser = new Login_User_BLL();
        private DataTable dtGetUserSecsion;
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                txtUsername.Focus(false,100);
                //if (LibCheckStatusInternet.CheckNet.CheckNetwork())
                //{
                //    CheckLicense();
                //}
                var cookie = Request.Cookies["login"];
                if (Session["login"] != null)
                {
                    if ((bool) (Session["login"]))
                    {
                        Response.Redirect(@"/Page/Theme_Default.aspx");
                    }
                }
                if (cookie != null)
                {
                    Response.Redirect(@"/Page/Theme_Default.aspx");
                }
            }
        }
        protected void btnLogin_Click(object sender, DirectEventArgs e)
        {
            if (txtUsername.Text == string.Empty)
            {
                clsFormat.Alert_ERROR("Thông Báo", "Tài khoản không được để trống !");
            }
            if (txtPassword.Text == string.Empty)
            {
                clsFormat.Alert_ERROR("Thông Báo", "Mật khẩu không được để trống !");
            }
            if (txtUsername.Text != string.Empty || txtPassword.Text != string.Empty)
            {
                CheckUserLogin();
            }
        }
        protected void btnCancel_Click(object sender, DirectEventArgs e)
        {
            Session["login"] = false;
            Response.Redirect(@"Login.aspx");
        }
        protected void btnRegister_Click(object sender, DirectEventArgs e)
        {
            if (String.IsNullOrEmpty(txtLicense.Text) && String.IsNullOrEmpty(txtKey.Text))
            {
                clsFormat.Alert_ERROR("Thông Báo", "Vui lòng nhập vào License và Key !");
            }
            else
            {
                ReRegisterLicense();
            }
        }
        #endregion

        #region[Method]
        private void CheckUserLogin()
        {
            #region[Using-Session]
            var cookie = new HttpCookie("login");
            string strsession = Encode.Encode.GetMD5(txtPassword.Text);
            dtGetUserSecsion = clsUser.GetDataUser(txtUsername.Text, strsession);
            if (LibCheckStatusInternet.CheckNet.CheckNetwork())
            {
                if (LibCheckUser.CheckUser.DeveloperCheck(txtUsername.Text, txtPassword.Text))
                {
                    Session["login"] = true;
                    Session["UserName"] = txtUsername.Text;
                    Session["Users_Id"] = -1;
                    Response.Redirect("/Page/Theme_Default.aspx");
                    WindowLogin.Close();
                }
            }
            else
            {
                clsFormat.Alert_ERROR("Thông Báo", "Tên đăng nhập hoặc tài khoản không chính xác !");
            }
            if (dtGetUserSecsion != null && dtGetUserSecsion.Rows.Count > 0)
            {
                if (txtUsername.Text.Trim() == dtGetUserSecsion.Rows[0]["UserName"].ToString() &&
                     strsession.Trim().ToUpper() == dtGetUserSecsion.Rows[0]["Passwords"].ToString())
                {
                    if (chkRemember.Checked)
                    {
                        Session["login"] = true;
                        
                        Session["UserName"] = txtUsername.Text;
                        Session["Passwords"] = dtGetUserSecsion.Rows[0]["Passwords"].ToString();
                        Session["Employee_Id"] = dtGetUserSecsion.Rows[0]["Employee_Id"].ToString();
                        Session["USer_Detail_Id"] = dtGetUserSecsion.Rows[0]["USer_Detail_Id"].ToString();
                        Session["IsActive"] = dtGetUserSecsion.Rows[0]["IsActive"].ToString();
                        Session["IsUsed"] = dtGetUserSecsion.Rows[0]["IsUsed"].ToString();
                        Session["Users_Id"] = dtGetUserSecsion.Rows[0]["Users_Id"].ToString();


                        cookie["UserName"] = Session["UserName"].ToString();
                        cookie["Employee_Id"] = Session["Employee_Id"].ToString();
                        cookie["USer_Detail_Id"] = Session["USer_Detail_Id"].ToString();
                        cookie["IsActive"] = Session["IsActive"].ToString();
                        cookie["IsUsed"] = Session["IsUsed"].ToString();
                        cookie["Users_Id"] = Session["Users_Id"].ToString();

                        cookie.Expires = DateTime.Now.AddDays(double.Parse(WebConfigurationManager.AppSettings["TimeOut"]));
                        Response.Cookies.Add(cookie);
                        Response.Redirect("/Page/Theme_Default.aspx");
                        WindowLogin.Close();
                    }
                    else
                    {
                        Session["login"] = true;
                        Session["UserName"] = txtUsername.Text;
                        Session["Passwords"] = dtGetUserSecsion.Rows[0]["Passwords"].ToString();
                        Session["Employee_Id"] = dtGetUserSecsion.Rows[0]["Employee_Id"].ToString();
                        Session["USer_Detail_Id"] = dtGetUserSecsion.Rows[0]["USer_Detail_Id"].ToString();
                        Session["IsActive"] = dtGetUserSecsion.Rows[0]["IsActive"].ToString();
                        Session["IsUsed"] = dtGetUserSecsion.Rows[0]["IsUsed"].ToString();
                        Session["Users_Id"] = dtGetUserSecsion.Rows[0]["Users_Id"].ToString();
                        Response.Redirect("/Page/Theme_Default.aspx");
                        WindowLogin.Close();
                    }
                }
            }
            else
            {
                clsFormat.Alert_ERROR("Thông Báo", "Tên đăng nhập,tài khoản không chính xác hoặc đã bị khoá");
                Session["login"] = false;
            }
            #endregion
        }
        private void CheckLicense()
        {
            var ClsLicense = new bll_sad_License();
            var dtCheckLicense = ClsLicense.GetLicense();
            if (dtCheckLicense != null && dtCheckLicense.Rows.Count > 0)
            {
                /*License,Key,Version,StatusActive,Row*/
                if (LibCheckLicense.CheckLicense.CheckedLicense(dtCheckLicense.Rows[0]["License"].ToString(),
                    dtCheckLicense.Rows[0]["Key"].ToString(), dtCheckLicense.Rows[0]["Version"].ToString(),
                    dtCheckLicense.Rows[0]["StatusActived"].ToString(), 1) == false)
                {
                    WindowLicense.Show();
                    WindowLogin.Close();
                }
                else
                {
                    WindowLicense.Close();
                    WindowLogin.Show();
                }
            }
            else
            {
                WindowLicense.Show();
            }
        }
        private void ReRegisterLicense()
        {
            if (LibCheckStatusInternet.CheckNet.CheckNetwork())
            {
                #region[Register]
                var ClsLicense = new bll_sad_License();
                var dtCheckLicense = ClsLicense.GetLicense();
                var dtGetLicense = LibCheckLicense.CheckLicense.GetLicense();
                if (dtCheckLicense != null && dtCheckLicense.Rows.Count > 0)
                {
                    if (dtGetLicense != null && dtGetLicense.Rows.Count > 0)
                    {
                        if (LibCheckLicense.CheckLicense.CheckedLicense(
                            txtLicense.Text, txtKey.Text,
                            dtGetLicense.Rows[1]["Version"].ToString(), dtCheckLicense.Rows[0]["StatusActived"].ToString(),
                            1))
                        {
                            try
                            {
                                var obj = new LicenseEt
                                {
                                    Id = 2,
                                    Customer = dtGetLicense.Rows[1]["Customer"].ToString(),
                                    LicenseType = dtGetLicense.Rows[1]["LicenseType"].ToString(),
                                    License = txtLicense.Text,
                                    Key = txtKey.Text,
                                    Version = dtGetLicense.Rows[1]["Version"].ToString()
                                };
                                bll_sad_License.RegisterLicense(obj);
                                CheckLicense();
                                WindowLicense.Close();
                                WindowLogin.Show();
                            }
                            catch (Exception ex)
                            {
                                clsFormat.Alert_ERROR("Lỗi", ex.Message);
                            }
                        }
                        else
                        {
                            clsFormat.Alert_ERROR("Lỗi", "Đăng ký không thành công !");
                        }
                    }
                }
                #endregion
            }
            else
            {
                clsFormat.Alert_ERROR("Lỗi", "Không có kết nối Internet !.Đăng ký không thành công");
            }
        }
        //private void WriteXml(string user_id, string username, string employee_id, string user_detail_id,
        //    string passwords,string IsActive,string IsUsed)
        //{
        //    try
        //    {
        //        var path = HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data/");
        //        var writer = System.Xml.XmlWriter.Create(path + "Session.xml");
        //        writer.WriteStartDocument();
        //        writer.WriteComment("This file is generated by the program.");
        //        writer.WriteStartElement("Session");
        //        writer.WriteAttributeString("login", "true");
        //        writer.WriteAttributeString("Users_Id", user_id);
        //        writer.WriteAttributeString("UserName", username);
        //        writer.WriteAttributeString("Employee_Id", employee_id);
        //        writer.WriteAttributeString("USer_Detail_Id", user_detail_id);
        //        writer.WriteAttributeString("Passwords", passwords);
        //        writer.WriteAttributeString("IsActive", IsActive);
        //        writer.WriteAttributeString("IsUsed", IsUsed);
        //        writer.WriteEndElement();
        //        writer.WriteEndDocument();
        //        writer.Flush();
        //        writer.Close();
        //    }
        //    catch (Exception ex)
        //    {
        //        clsFormat.Alert_ERROR("Lỗi", ex.Message);
        //    }
        //}
        #endregion
    }
}